package com.mission.schedule.activity

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ScrollView
import android.widget.Toast
import com.android.volley.AuthFailureError
import com.android.volley.DefaultRetryPolicy
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.google.gson.Gson
import com.lcf.refreshlibrary.PullToRefreshBase
import com.mission.schedule.R
import com.mission.schedule.applcation.App
import com.mission.schedule.constants.ShareFile
import com.mission.schedule.constants.URLConstants
import com.mission.schedule.my160920.ScrollLinearLayoutManager
import com.mission.schedule.my160920.widget.EditTextC
import com.mission.schedule.utils.SharedPrefUtil
import com.mission.schedule.widget.SwipeLinearLayout
import com.nostra13.universalimageloader.core.DisplayImageOptions
import com.nostra13.universalimageloader.core.ImageLoader
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener
import kotlinx.android.synthetic.main.adapter_addfriends.view.*
import kotlinx.android.synthetic.main.fragment_newfriend.*
import java.util.*

/**
 * Created by liwei on 2018/2/4.
 */


class NewMyFriendActivity: Activity() {
    private var imageLoader: ImageLoader? = null
    private val animateFirstListener = AnimateFirstDisplayListener()
    private var options: DisplayImageOptions? = null

    internal var sharedPrefUtil: SharedPrefUtil? = null

    internal var isShow = false

    var userId: String = ""
    private var isYouKe: String = ""
    var itemsBeanList: ArrayList<NewFriendsActivity.newFriendBean.PageBean.ItemsBean> = arrayListOf()
    var adapter = Adapter()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.fragment_newfriend)
        init()
    }

    override fun onResume() {
        super.onResume()
        init()
    }

    private fun init() {
        itemsBeanList = App.getDBcApplication().getAllNewFriendData(userId, false)

        imageLoader = ImageLoader.getInstance()
        sharedPrefUtil = SharedPrefUtil(this@NewMyFriendActivity, ShareFile.USERFILE)
        userId = sharedPrefUtil!!.getString(this@NewMyFriendActivity, ShareFile.USERFILE, ShareFile.USERID, "0")
        isYouKe = sharedPrefUtil!!.getString(this@NewMyFriendActivity, ShareFile.USERFILE, ShareFile.ISYOUKE, "1")
        isYouKe = sharedPrefUtil!!.getString(this@NewMyFriendActivity, ShareFile.USERFILE, ShareFile.ISYOUKE, "1")

        if (sharedPrefUtil!!.getString(this@NewMyFriendActivity,
                ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0") == "-1") {
            options = DisplayImageOptions.Builder()
                    .showStubImage(R.mipmap.b1)
                    .showImageForEmptyUri(R.mipmap.b1)
                    .showImageOnFail(R.mipmap.b1).cacheInMemory(true)
                    .cacheOnDisc(true).cacheInMemory(true)
                    .bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
                    .build()
        } else {
            options = DisplayImageOptions.Builder()
                    .showStubImage(R.mipmap.turh)
                    .showImageForEmptyUri(R.mipmap.turh)
                    .showImageOnFail(R.mipmap.turh).cacheInMemory(true)
                    .cacheOnDisc(true).cacheInMemory(true)
                    .bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
                    .build()
        }

        val slm = ScrollLinearLayoutManager(this)
        slm.setScrollEnabled(false)
        recyclerview.layoutManager = slm
        recyclerview.adapter = adapter
        recyclerview.itemAnimator = DefaultItemAnimator()

        myfriend_pull_refresh_view.setOnRefreshListener(object : PullToRefreshBase.OnRefreshListener2<ScrollView> {


            override fun onPullDownToRefresh(
                    refreshView: PullToRefreshBase<ScrollView>) {
                AsyncNewFriend()
            }

            override fun onPullUpToRefresh(
                    refreshView: PullToRefreshBase<ScrollView>) {
                myfriend_pull_refresh_view.onRefreshComplete()
            }
        })

        sousuocontent_et.setEdittextCoutomListener(object : EditTextC.EdittextCoutomListener {
            override fun enter(index: Int, text: String) {
                if (!sousuocontent_et.text.toString().isEmpty()) {
                    val zorana = Intent(this@NewMyFriendActivity, NewFriendsActivity::class.java)
                    zorana.putExtra("titleid", "00")
                    zorana.putExtra("title", "搜索")
                    zorana.putExtra("content", sousuocontent_et.text.toString())
                    startActivity(zorana)
                    sousuocontent_et.setText("")
                } else {
                    Toast.makeText(this@NewMyFriendActivity, "请输入搜索内容", Toast.LENGTH_SHORT).show()
                }
            }

            override fun delete(index: Int, text: String?) {
            }

            override fun textchange(index: Int, hastext: Boolean) {
            }
        })

        top_ll_left.setOnClickListener {
            finish()
        }
    }

    private class AnimateFirstDisplayListener : SimpleImageLoadingListener() {

        override fun onLoadingComplete(imageUri: String, view: View,
                                       loadedImage: Bitmap) {
            val imageView = view as ImageView?
            // 是否第一次显示
            val firstDisplay = !displayedImages.contains(imageUri)
            if (firstDisplay) {
                // 图片淡入效果
                FadeInBitmapDisplayer.animate(imageView, 500)
                displayedImages.add(imageUri)
            }
        }

        companion object {

            internal val displayedImages: MutableList<String> = Collections
                    .synchronizedList(LinkedList())
        }
    }


    private fun AsyncNewFriend() {
        val request = object : StringRequest(Method.POST, URLConstants.查询常用联系人刷新信息,
                Response.Listener { result ->
                    if (!TextUtils.isEmpty(result)) {
                        val gson = Gson()
                        val updateUserBean = gson.fromJson<UpdateUserBean>(result, UpdateUserBean::class.java!!)
                        if (updateUserBean.status == 0) {
                            val list = updateUserBean.list
                            for (bean in list) {
                                App.getDBcApplication().updateNewFriendData(bean.uId, bean.uPortrait, bean.uNickName)
                            }
                            itemsBeanList = App.getDBcApplication().getAllNewFriendData(userId, false)
                            recyclerview.adapter = adapter
                        }
                    }
                    myfriend_pull_refresh_view.onRefreshComplete()
                }, Response.ErrorListener { myfriend_pull_refresh_view.onRefreshComplete() }) {
            @Throws(AuthFailureError::class)
            override fun getParams(): Map<String, String> {
                val map = HashMap<String, String>()
                map.put("uId", userId)
                return map
            }
        }
        request.tag = "updateuser"
        request.retryPolicy = DefaultRetryPolicy(2000, 1, 1.0f)
        App.getHttpQueues().add(request)
    }


    inner class Adapter : RecyclerView.Adapter<Adapter.Holder>() {

        var swipeLinearLayouts: MutableList<SwipeLinearLayout> = ArrayList()

        override fun getItemCount(): Int {
            return itemsBeanList.size
        }

        override fun onBindViewHolder(holder: Adapter.Holder, position: Int) {
            if (itemsBeanList.size > 0) {

                swipeLinearLayouts.add(holder.itemView.swipeLayout)

                holder.itemView.swipeLayout.setOnSwipeListener { thisSll, isHorizontal ->
                    if (!isHorizontal) {
                        swipeLinearLayouts
                                .forEach { it.scrollAuto(SwipeLinearLayout.DIRECTION_SHRINK) }
                    } else {
                        swipeLinearLayouts
                                .filter { it != thisSll }
                                .forEach {
                                    //划开一个sll， 其他收缩
                                    it.scrollAuto(SwipeLinearLayout.DIRECTION_SHRINK)
                                }
                    }
                }

                holder.itemView.person_ll.setOnClickListener {
                    val intent = Intent(this@NewMyFriendActivity, MyKzoneActivity::class.java)
                    intent.putExtra("userid", itemsBeanList[position].puid.toString())
                    intent.putExtra("name", itemsBeanList[position].pname)
                    intent.putExtra("pimage", itemsBeanList[position].pimgs)
                    startActivity(intent)
                }

                holder.itemView.tv_delete.setOnClickListener {
                    holder.itemView.swipeLayout.scrollAuto(SwipeLinearLayout.DIRECTION_SHRINK)
                    if (App.getDBcApplication().getNewFriendUpdateState(itemsBeanList[position].id) == 1) {
                        App.getDBcApplication().deleteNewFriendData(itemsBeanList[position].id, userId, true)
                    } else {
                        App.getDBcApplication().deleteNewFriendData(itemsBeanList[position].id, userId, false)
                    }
                    itemsBeanList.remove(itemsBeanList[position])
                    notifyItemRemoved(position)
                }

                var nums = App.getDBcApplication().getAllSendRepeatNoteData(userId, itemsBeanList[position].puid, -1,false).size
                var name = if (itemsBeanList[position].pname == null) {
                    "@无名称"
                } else {
                    "@${itemsBeanList[position].pname}"
                }
//                var numsn = if (nums == 0) "" else "重复($nums)"
                if (nums == 0) {
                    holder.itemView.repeat_task_nums.visibility = View.GONE
                } else {
                    holder.itemView.repeat_task_nums.visibility = View.VISIBLE
                    holder.itemView.repeat_task_nums.text = "重复($nums)"
                }
//                var newname = "$name $numsn"
//                val style = SpannableStringBuilder(newname)
//                style.setSpan(ForegroundColorSpan(this@NewMyFriendActivity.resources.getColor(R.color.gongkai_txt)), (newname.length - numsn.length), newname.length,
//                        Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
                holder.itemView.friendname_tv.text = name

                holder.itemView.friendtag_tv.text = "暂无消息!"
                var imageUrl = ""
                if (!itemsBeanList[position].pimgs.isEmpty()) {
                    imageUrl = itemsBeanList[position].pimgs.toString()
                }
                val imagery = URLConstants.图片 + imageUrl + "&imageType=2&imageSizeType=3"
                imageLoader!!.displayImage(imagery, holder.itemView.friend_img, options,
                        animateFirstListener)
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Adapter.Holder {
            val view = LayoutInflater.from(this@NewMyFriendActivity).inflate(R.layout.adapter_addfriends, parent, false)
            return Holder(view)
        }

        inner class Holder(view: View) : RecyclerView.ViewHolder(view)

    }

    internal inner class UpdateUserBean(var status: Int = 0, var downTime: String, var tDelList: Any, var list: List<ListBean>) {
        inner class ListBean(var uId: Int = 0, var uPortrait: String, var uNickName: String)
    }

}